import { Inject, Injectable } from '@nestjs/common';
import { RedisClientType } from 'redis';

import { ConstantEnum } from '../enums';

@Injectable()
export class RedisService {
  @Inject(ConstantEnum.REDIS_CLIENT)
  private redisClient: RedisClientType;

  async get<T = unknown>(key: string): Promise<T> {
    const data = (await this.redisClient.get(key)) || 'null';
    return JSON.parse(data);
  }

  /**
   *
   *
   * @param {string} key
   * @param {*} value
   * @param {number} [ttl] 过期时间，单位秒
   * @memberof RedisService
   */
  async set(key: string, value: any, ttl?: number) {
    const data = JSON.stringify(value);
    await this.redisClient.set(key, data);
    if (ttl) {
      await this.redisClient.expire(key, ttl);
    }
  }

  async del(key: string) {
    await this.redisClient.del(key);
  }
}
